﻿
'###########################################
'###  BIG THX TO: jMerliN & clearscreen  ###
'###           www.SREmu.org             ###
'###########################################

Public Class cSecurityByteGen

    Protected pByteSeed(2) As Int32
    Protected pCRCseed As Int32
    Dim Table() As UInt32
    Sub addSecurity(ByRef packet() As Byte)
        packet(4) = 0
        packet(5) = 0
        packet(4) = GenerateCountByte()
        packet(5) = GenerateCRCByte(packet, packet.GetUpperBound(0) + 1)
    End Sub

    Private Function GenerateCRCByte(ByVal packet As Byte(), ByVal len As Int32) As Byte

        Dim checksum As UInt32 = 4294967295
        Dim moddedseed As Int32 = pCRCseed << 8
        For i As Int32 = 0 To len - 1
            Dim test As Int64 = Table(moddedseed + ((packet(i) Xor checksum) And &HFF))
            checksum = checksum >> 8 Xor test
        Next
        Dim result As Int32 = ((checksum >> 24) And &HFF) + ((checksum >> 8) And &HFF) + ((checksum >> 16) And &HFF) + (checksum And &HFF)
        result = result And &HFF
        Return result
    End Function

    Private Function GenerateCountByte() As Byte
        Dim retVal As Int32 = pByteSeed(2) * ((Not pByteSeed(0)) + pByteSeed(1))
        retVal = &HFF And retVal
        retVal = retVal Xor (retVal >> 4)
        pByteSeed(0) = retVal
        Return retVal
    End Function
    Sub Init(ByVal CounterSeed As Int32, ByVal crcSeed As Int32)
        generateGenerateByteSeed(CounterSeed)
        pCRCseed = crcSeed
    End Sub


    Sub New()
        Using r As New IO.BinaryReader(New IO.MemoryStream(My.Resources.table))
            ReDim Table((&H10000UL - 1))
            For i As UInt32 = 0 To &H10000UL - 1
                Table(i) = r.ReadUInt32()
            Next
        End Using
    End Sub

    Private Function GenerateValue(ByRef val As UInt32) As UInt32
        For i As Int16 = 0 To 31
            val = (((((((((((val >> 2) Xor val) >> 2) Xor val) >> 1) Xor val) >> 1) Xor val) >> 1) Xor val) And 1) Or ((((val And 1) << 31) Or (val >> 1)) And &HFFFFFFFE)
        Next
        Return val
    End Function

    Private Sub generateGenerateByteSeed(ByVal seed As Int32)
        If (seed = 0) Then seed = &H9ABFB3B6
        Dim mut1 As UInt32 = seed
        Dim mut2 As UInt32 = GenerateValue(mut1)
        Dim mut3 As UInt32 = GenerateValue(mut1)
        Dim mut4 As UInt32 = GenerateValue(mut1)
        GenerateValue(mut1)
        Dim byte1 As Byte = (mut1 And &HFF) Xor (mut4 And &HFF)
        Dim byte2 As Byte = (mut2 And &HFF) Xor (mut3 And &HFF)
        If byte1 = 0 Then byte1 = 1
        If byte2 = 0 Then byte2 = 1
        pByteSeed(0) = byte1 Xor byte2
        pByteSeed(1) = byte2
        pByteSeed(2) = byte1
    End Sub



End Class



